//
//  ViewController.m
//  iBeacon
//
//  Created by Apple on 12/18/15.
//  Copyright © 2015 Apple. All rights reserved.
//

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <CoreBluetooth/CoreBluetooth.h>
#import "AprilBeaconSDK.h"
#import "ABTransmitters.h"
static NSString * const kServiceUUID = @"1C85D7B7-17FA-4362-82CF-85DD0B76A9A5";
static NSString * const kCharacteristicUUID = @"CBE9ED38-A126-009D-8D8B-A918A89BDDFC";
@interface ViewController ()<CLLocationManagerDelegate,ABBeaconManagerDelegate>
@property CLLocationManager *locationManager;
@property CLBeaconRegion *beaconRegion;

@property (nonatomic, strong) ABBeaconManager *beaconManager;
@property (nonatomic, strong) NSMutableArray *tableData;
@end

@implementation ViewController


-(void)viewDidLoad{
    self.beaconManager = [[ABBeaconManager alloc] init];
    self.beaconManager.delegate = self;
    
    [self.beaconManager requestAlwaysAuthorization];
    
    _tableData = [NSMutableArray array];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self startRangeBeacons];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self stopRangeBeacons];
}
#pragma mark - ABBeaconManagerDelegate
- (void)beaconManager:(ABBeaconManager *)manager didEnterRegion:(ABBeaconRegion *)region
{
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.alertBody = @"Enter monitoring region";
    notification.soundName = UILocalNotificationDefaultSoundName;
    [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
}

- (void)beaconManager:(ABBeaconManager *)manager didExitRegion:(ABBeaconRegion *)region
{
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.alertBody = @"Exit monitoring region";
    notification.soundName = UILocalNotificationDefaultSoundName;
    [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
}



- (void)beaconManager:(ABBeaconManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(ABBeaconRegion *)region
{
    [_tableData removeAllObjects];
    for(ABBeacon *beacon in beacons){
        NSLog(@"%f",beacon.distance.doubleValue);
        [_tableData addObject:beacon];
    }
    NSLog(@"beacons = %@", beacons);
    [self.tableView reloadData];

}

- (void)beaconManager:(ABBeaconManager *)manager rangingBeaconsDidFailForRegion:(ABBeaconRegion *)region withError:(NSError *)error
{

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.tableData.count;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"April"];
    ABBeacon* ab= [self.tableData objectAtIndex:indexPath.row];
    NSString *proximity;
    switch (ab.proximity) {
        case CLProximityFar:
            proximity = @"Far";
            break;
        case CLProximityImmediate:
            proximity = @"Immediate";
            break;
        case CLProximityNear:
            proximity = @"Near";
            break;
        default:
            proximity = @"Unknown";
            break;
    }
    //cell.detailTextLabel.text = [NSString stringWithFormat:@"Major: %@, Minor: %@, Acc: %.2fm, proximity=%@", ab.major, ab.minor, [ab.distance floatValue], proximity];
    cell.detailTextLabel.text=proximity;
    cell.textLabel.text=[NSString stringWithFormat:@"%0.2f",[ab.distance floatValue]];
    //cell.textLabel.text=ab.proximityUUID.UUIDString;
    return cell;
}


#pragma mark - Custom methods

- (void)startRangeBeacons
{
    [self stopRangeBeacons];
    
    ABTransmitters *tran = [ABTransmitters sharedTransmitters];
    [[tran transmitters] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSUUID *proximityUUID = [[NSUUID alloc] initWithUUIDString:obj[@"uuid"]];
        NSString *regionIdentifier = obj[@"uuid"];
        
        ABBeaconRegion *beaconRegion;
        beaconRegion = [[ABBeaconRegion alloc] initWithProximityUUID:proximityUUID
                                                          identifier:regionIdentifier];
        beaconRegion.notifyOnEntry = YES;
        beaconRegion.notifyOnExit = YES;
        beaconRegion.notifyEntryStateOnDisplay = YES;
        //[_beaconManager startRangingBeaconsInRegion:beaconRegion];
        [_beaconManager startMonitoringForRegion:beaconRegion];
    }];
}

- (void)stopRangeBeacons
{
    ABTransmitters *tran = [ABTransmitters sharedTransmitters];
    [[tran transmitters] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSUUID *proximityUUID = [[NSUUID alloc] initWithUUIDString:obj[@"uuid"]];
        NSString *regionIdentifier = obj[@"uuid"];
        
        ABBeaconRegion *beaconRegion;
        beaconRegion = [[ABBeaconRegion alloc] initWithProximityUUID:proximityUUID
                                                          identifier:regionIdentifier];
        //[_beaconManager stopRangingBeaconsInRegion:beaconRegion];
        [_beaconManager stopMonitoringForRegion:beaconRegion];
    }];
    
}
/*
- (void)viewDidLoad {
    [super viewDidLoad];
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    [self.locationManager requestAlwaysAuthorization];
    NSLog(@"%@",[UIDevice currentDevice].identifierForVendor);
    _beaconRegion =[[CLBeaconRegion alloc]initWithProximityUUID:[UIDevice currentDevice].identifierForVendor identifier:@"just for test"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    if (status == kCLAuthorizationStatusAuthorizedAlways) {
        _beaconRegion.notifyOnEntry = YES;
        _beaconRegion.notifyOnExit = YES;
        _beaconRegion.notifyEntryStateOnDisplay = YES;
        [self.locationManager startMonitoringForRegion:_beaconRegion];
        [self.locationManager startRangingBeaconsInRegion:_beaconRegion];//开始RegionBeacons
    }
    
}
#pragma delegate
- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error {
    NSLog(@"Failed monitoring region: %@", error);
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"Location manager failed: %@", error);
}

- (void)locationManager:(CLLocationManager *)manager
        didRangeBeacons:(NSArray *)beacons
               inRegion:(CLBeaconRegion *)region
{
    for (CLBeacon *beacon in beacons) {
        NSLog(@"%@",beacon);
    }
}
-(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region{
    
    
    
}
*/
@end
